import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Alert,
  Dimensions,
} from 'react-native';

import styles from '../order/editOrderStyle';
import CustomListView from '../global/CustomListView';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';
import api from '../../services/api';
import _ from 'lodash';
import ToastTip from '../global/ToastTip';
import * as config from '../../constants/apiConfig';
import Communications from 'react-native-communications';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class OwnerListApprove extends Component {
    constructor(props) {
		super(props);

		this.state = {
			currentPage: 1,
            noData: false,
            totalCount:0,
            dataList:[],
		};

        // this._page = 0;
        this.totalpage = 0;
        this.pagesize = 10;
        this.list = [];

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    // _onNavigatorEvent(event){
    //     if(event.id == "didAppear"){
    //         this.onLoad();
    //     }
    // }

    componentDidMount() {
        this._mounted = true;
        this.onLoad();
    }

    onLoad(page){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._withdrawByList._pullToRefreshListView.beginRefresh(true);
    }

    componentWillUnmount () {
        this._mounted = false;
        this.timeIndex && clearTimeout(this.timeIndex);
    }

    _onSearchResultListItemPress(rowData){
        // this.props.parent.setState({addressFirst: `${rowData.first_address}${rowData.second_address}`});
    }

    async _getWithdrawList(page){
        let list;

        this.setState({ currentPage: page || 1 });
        list = await api.post('/housekeeper/ownerlistnotapproved', {
                       page: page || 1,
                       pagesize: this.pagesize
                    });

        if(list.cd == 1){
            this.refs.toast.show(list.msg);
            this._withdrawByList._pullToRefreshListView.endRefresh(false);
            return;
        }

       if(Platform.OS == 'ios') {
           this._endWithdrawList(list.data);
       } else {
           this.timeIndex = setTimeout(() => {
               this._endWithdrawList(list.data);
           }, 200);
       }
    }

    // _updateListView(){
    //     let {actions, dispatch} = this.props;
    //     let action;
    //     if(this.props.status == 1){//收藏地址
    //         action = actions.address.store_change(this.list);
    //     }else {
    //         action = actions.address.history_change(this.list);
    //     }
    //
    //     dispatch(action);
    // }

    _endWithdrawList(list){

        console.log("########", list);

        this.totalpage = list.total_page;
        this.list = list.res;
        this.count = list.count;

        if(!this._mounted){
            return;
        }

        //设置mark
        this.props.parent.updateMarkNum([0, this.count]);

        if(this.list.length==0){
            this.setState({noData: true});
            return;
        }

        this._withdrawByList.setState({
            dataList: list.res,
            dataSource: this._withdrawByList._dataSource.cloneWithRows(list.res)
        });

        this.setState({totalCount: list.count, dataList: list.res});

        this._activityIndicator.setState({ visible: false,});
        this._withdrawByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {
		if (this.state.currentPage !== this.totalpage) {

			let page;
            page = this.state.currentPage + 1;
            this.setState({ currentPage: page });

            let list;
            list = await api.post('/housekeeper/ownerlistnotapproved', {
                           page:page,
                           pagesize: this.pagesize
                        });

            if(list.cd == 1){
                this.refs.toast.show(list.msg);
                this._withdrawByList._pullToRefreshListView.endRefresh(false);
                return;
            }
        //    const data = this.list;
           const newData = list.data.res;
           newData.map((item, index) => this.list.push(item));

           this._withdrawByList.setState({
               dataList: this.list,
               dataSource: this._withdrawByList._dataSource.cloneWithRows(this.list),
           });
           this._withdrawByList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._withdrawByList._pullToRefreshListView.endLoadMore(true);
        }
	}

    _onRefresh(){
        this._getWithdrawList();
    }

    _onLoadMore(){
        this._retrieveNextPage();
    }

    _rejectedUser(data){
        Alert.alert(
          '拒绝',
          '确定拒绝该用户吗？',
          [
            {text: '取消', onPress: () => {}, style: 'cancel'},
            {text: '确定', onPress: () => {
                this._rejectedAction(data);
            }},
          ],
          { cancelable: false }
       );
    }

    _approvedUser(data){
        this.props.navigator.push({
            title: "审核通过",
            backButtonTitle:'',
			screen: 'housekeeperapp.approvedform',
			passProps: {
                ownerinfo: data
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		}, );
    }

    async _rejectedAction(data){

        let res = await api.post("/account/app/rejected",{id: data.id});

        if(res.cd == 1){
            this.refs.toast.show(res.msg);
        }else {
            let { session } = this.props;
            let web_base_url = "";
            if (session && session.user && session.user.product && session.user.product.baseUrl) {
                console.log('test---------------000000000dddddddsaaaaaaaaasf',session.user.product);
                web_base_url = session.user.product.baseUrl;
            }else{
                web_base_url = config.WEB_BASE_URL;
            }
            this.refs.toast.show('操作完成', 500, async()=>{
                let json = JSON.stringify({
                                "touser":data.wxOpenId,
                                "msgtype":"text",
                                "text":
                                {
                                     "content":"您好，很抱歉您提交的注册信息审核未通过。\n若您的信息填写有误，请重新填写，如有疑问，请致电\n400-9007-808 \n<a href='"+web_base_url+"/citylist?id="+data.id+"'>重新填写信息>></a>",
                                }
                            });

                let send_res = await api.post('/wx/customsend',{json});
                // 刷新页面
                this._getWithdrawList(this.state.currentPage);
            });
        }
    }

    _firePhone(phone){
        Communications.phonecall(phone, true);
    }

    _renderRow(rowData, sectionID, rowID){

        return (
            <View style={{paddingLeft:15,paddingTop:15,paddingBottom:15,marginBottom:10,backgroundColor:'#fff',borderTopWidth: StyleSheet.hairlineWidth,borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                {/* <View style={{flex:1, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE", paddingBottom: 15}}>
                    <Text style={{fontSize: 18, color: '#555555',}}>{rowData.phone}</Text>
                    <Text style={{fontSize: 15, color: '#7B7B7B', marginTop: 6, }}>{rowData.homeAddress}</Text>
                </View> */}
                <View style={{paddingBottom:15,flexDirection: 'row',alignItems:'center',borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                    <View style={{borderRightWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE",flex:1}}>
                        <Text style={{fontSize: 18, color: '#555555',}}>{rowData.name||decodeURIComponent(rowData.wxName) }<Text style={{fontSize:15, color: '#7B7B7B',marginLeft:11}}>{' '+rowData.phone}</Text></Text>
                        <Text style={{fontSize: 15, color: '#7B7B7B', marginTop: 6, }}>{rowData.homeAddress}</Text>
                    </View>
                    <TouchableOpacity onPress={this._firePhone.bind(this, rowData.phone)} style={{justifyContent: 'flex-end',marginRight:22,marginLeft:22}}>
                        <Image source={require('../../../img/hk_phone_icon.png')}/>
                    </TouchableOpacity>
                </View>
                {rowData.approved=='rejected'?
                <View style={{flex:1, flexDirection: 'row', justifyContent: 'flex-end'}}>
                    <Text style={{fontSize: 15, width: 55,paddingTop: 3, paddingBottom: 3, color: '#B5B5B5', textAlign: 'center', marginRight: 15, marginTop: 15, backgroundColor: '#DDDDDD', borderRadius: 2, overflow: 'hidden'}}>已拒绝</Text>
                </View>:
                <View style={{flex:1, flexDirection: 'row', justifyContent: 'flex-end'}}>
                    <TouchableOpacity onPress={this._rejectedUser.bind(this, rowData)} style={{justifyContent: 'flex-end',marginRight: 10, marginTop: 15,}}>
                        <Text style={styles.notActiveText}>拒绝</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this._approvedUser.bind(this, rowData)} style={{justifyContent: 'flex-end',marginRight:15, marginTop: 15,}}>
                        <Text style={styles.activeText}>通过</Text>
                    </TouchableOpacity>
                </View>}
            </View>
        );
    }

    _renderNodata(){
        return (
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无审核的业主</Text>
            </View>
        );
    }

    render() {
        return (
            this.state.noData?this._renderNodata():
            <View style={{flex: 1, backgroundColor: '#f3f3f3',}}>
                <View style={{paddingTop:10,paddingBottom:10}}>
                    <Text style={{fontSize: 15, color: '#7B7B7B',textAlign:'center'}}>需审核业主：{this.state.totalCount}人</Text>
                </View>
                <CustomListView
                    contentStyle={{backgroundColor:"#f3f3f3"}}
                    ref={ (component) => this._withdrawByList = component }
                    dataList={this.state.dataList}
                    onRefresh={this._onRefresh.bind(this)}
                    onLoadMore={this._onLoadMore.bind(this)}
                    renderRow ={this._renderRow.bind(this)}
                />
                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 70) / 2, }}
                    color={'#a9a9a9'}/>
                <ToastTip ref="toast" offsetY={160}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
OwnerListApprove = connectHelper(state => state)(OwnerListApprove);

module.exports = OwnerListApprove;
